package com.ohuang.wallpapermanager

import android.app.WallpaperManager
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.widget.Toast


object WallPaperManager {

    fun setWallPaperForFile(filePath:String,context: Context,isLock:Boolean){
        val bitmap = BitmapFactory.decodeFile(filePath)
        if (bitmap == null) {
            return
        }
        if (isLock) {
            setLockScreenWallpaper(bitmap, context)
        }else{
            setHomeScreenWallpaper(bitmap, context)
        }
    }

    fun setWallPaperForUri(uri: Uri,context: Context,isLock:Boolean) {
       val bitmap = BitmapFactory.decodeStream(context.contentResolver.openInputStream(uri))
        if (bitmap == null) {
            Toast.makeText(context, "图片加载失败", Toast.LENGTH_SHORT).show()
            return
        }
        if (isLock) {
            setLockScreenWallpaper(bitmap, context)
        }else{
            setHomeScreenWallpaper(bitmap, context)
        }
    }


    private fun setHomeScreenWallpaper(bitmap: Bitmap,context: Context) {
        val wallpaperManager = WallpaperManager.getInstance(context)
        try {
            // 设置桌面壁纸
            wallpaperManager.setBitmap(bitmap,null, true, WallpaperManager.FLAG_SYSTEM)

        } catch (e: Exception) {
            handleException("设置桌面壁纸时出错", e)
        }
    }

    private fun handleException(s: String, e: Exception) {
           e.printStackTrace()
    }

    private fun setLockScreenWallpaper(bitmap: Bitmap,context: Context) {
        val wallpaperManager = WallpaperManager.getInstance(context)
        try {
            // 尝试设置锁屏壁纸
            // 注意：FLAG_LOCK可能会根据Android版本和设备有所不同
            wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK)

        } catch (e: Exception) {
            handleException("设置锁屏壁纸时出错", e)
        }
    }

}